<template>
  <div v-if="isDialog" style="align-items: center; width: 100%; height: 50px">
    <span
      style="
        font-size: 25px;
        align-content: center;
        font-weight: 600;
        display: flex;
        justify-content: center;
      "
    >
      忘记密码
    </span>
  </div>
  <div v-else class="login-title">
    <img class="icon" src="@/assets/image/logo.png" alt="logo" />
    <h2 class="title">
      {{ WEBSITE_NAME }}
    </h2>
  </div>

  <el-form ref="forgotFormRef" :model="forgotForm" :rules="forgotRules">
    <el-form-item prop="email">
      <el-input v-model="forgotForm.email" placeholder="请输入注册邮箱" auto-complete="off">
        <template #prefix>
          <svg-icon icon-class="email" />
        </template>
        <template #append>
          <el-select v-model="emailSuffix" class="emailSelect" placeholder="邮箱后缀">
            <el-option label="@qq.com" value="@qq.com" />
            <el-option label="@163.com" value="@163.com" />
          </el-select>
        </template>
      </el-input>
    </el-form-item>

    <el-form-item prop="verifyCode">
      <el-input v-model="forgotForm.verifyCode" placeholder="请输入验证码" auto-complete="off">
        <template #prefix>
          <svg-icon icon-class="captcha" />
        </template>
        <template #suffix>
          <el-button :disabled="isCountingDown" link type="primary" @click="sendVerifyCode">
            {{ countDownText }}
          </el-button>
        </template>
      </el-input>
    </el-form-item>

    <el-form-item prop="newPassword">
      <el-input
        v-model="forgotForm.newPassword"
        placeholder="请输入新密码"
        :type="passwordType"
        auto-complete="off"
        @input="checkPasswordStrength"
      >
        <template #prefix>
          <el-tooltip
            effect="dark"
            placement="right"
            :content="`密码要求：
            · 长度至少8位
            · 包含大小写字母
            · 包含数字
            · 包含特殊字符`"
          >
            <svg-icon icon-class="password" />
          </el-tooltip>
        </template>
        <template #suffix>
          <svg-icon
            :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
            style="cursor: pointer"
            @click="showPassword"
          />
        </template>
      </el-input>
      <div v-if="forgotForm.newPassword" class="password-strength">
        <div class="strength-label">密码强度：</div>
        <div class="strength-bars">
          <div
            class="strength-bar"
            :class="{
              weak: passwordStrength >= 1,
              medium: passwordStrength >= 2,
              strong: passwordStrength >= 3
            }"
          />
          <div
            class="strength-bar"
            :class="{
              medium: passwordStrength >= 2,
              strong: passwordStrength >= 3
            }"
          />
          <div
            class="strength-bar"
            :class="{
              strong: passwordStrength >= 3
            }"
          />
        </div>
        <span
          class="strength-text"
          :class="{
            'text-weak': passwordStrength === 1,
            'text-medium': passwordStrength === 2,
            'text-strong': passwordStrength === 3
          }"
        >
          {{ passwordStrengthText }}
        </span>
      </div>
    </el-form-item>

    <el-form-item style="width: 100%">
      <el-button :loading="loading" class="login-btn" type="primary" @click="handleResetPassword">
        重置密码
      </el-button>
    </el-form-item>

    <!-- 返回登录 -->
    <div class="text-center mt-4">
      <p class="mb-2">
        <span>想起密码了？</span>
        <el-button link type="primary" @click="$emit('switch-mode')">返回登录</el-button>
      </p>
    </div>
  </el-form>
</template>

<script lang="ts" setup>
import { ref, reactive, computed } from 'vue';
import type { FormInstance, FormItemRule } from 'element-plus';
import { ElNotification } from 'element-plus';
import SvgIcon from '@/components/common/SvgIcon/index.vue';
import { WEBSITE_NAME } from '@/constants';

const props = defineProps({
  isDialog: {
    type: Boolean,
    default: false
  }
});

// 定义事件
const emit = defineEmits(['switch-mode', 'reset-success']);

const forgotFormRef = ref<FormInstance>();
const passwordType = ref('password');
const loading = ref(false);

// 忘记密码表单
const forgotForm = reactive({
  email: '',
  verifyCode: '',
  newPassword: ''
});

// 验证码倒计时
const isCountingDown = ref(false);
const countDown = ref(60);
const countDownText = ref('发送验证码');

// 密码强度校验
const passwordStrength = ref(0);
const passwordStrengthText = computed(() => {
  switch (passwordStrength.value) {
    case 1:
      return '简单';
    case 2:
      return '中等';
    case 3:
      return '强';
    default:
      return '';
  }
});

const checkPasswordStrength = () => {
  const password = forgotForm.newPassword;
  if (!password) {
    passwordStrength.value = 0;
    return;
  }

  let score = 0;

  // 基本要求：8位以上
  if (password.length >= 8) score++;

  // 包含数字和字母
  if (/(?=.*[A-Za-z])(?=.*\d)/.test(password)) score++;

  // 包含特殊字符和大小写字母
  if (/(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*])/.test(password)) score++;

  passwordStrength.value = score;
};

// 密码验证规则
const validatePassword = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error('请输入密码'));
  } else if (value.length < 8) {
    callback(new Error('密码长度至少8位'));
  } else if (!/(?=.*[A-Za-z])(?=.*\d)/.test(value)) {
    callback(new Error('密码必须包含字母和数字'));
  } else if (!/(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*])/.test(value)) {
    callback(new Error('密码必须包含大小写字母和特殊字符'));
  } else {
    callback();
  }
};

const forgotRules = reactive<Record<string, FormItemRule[]>>({
  email: [
    {
      required: true,
      message: '请输入邮箱地址',
      trigger: 'blur'
    },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (!value) {
          callback(new Error('请输入邮箱地址'));
        } else if (!/^[a-zA-Z0-9_-]+$/.test(value)) {
          callback(new Error('邮箱前缀只能包含字母、数字、下划线和连字符'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  verifyCode: [
    {
      required: true,
      message: '请输入验证码',
      trigger: 'blur'
    },
    {
      min: 6,
      max: 6,
      message: '验证码长度为6位',
      trigger: 'blur'
    }
  ],
  newPassword: [
    {
      required: true,
      message: '请输入新密码',
      trigger: 'blur'
    },
    {
      validator: validatePassword,
      trigger: 'blur'
    }
  ]
});

// 显示密码图标
const showPassword = () => {
  passwordType.value = passwordType.value === 'password' ? 'text' : 'password';
};

const emailSuffix = ref('@qq.com');

// 发送验证码
const sendVerifyCode = async () => {
  const fullEmail = forgotForm.email + emailSuffix.value;
  if (!forgotForm.email) {
    ElNotification({
      title: '提示',
      message: '请先输入邮箱地址',
      type: 'warning'
    });
    return;
  }

  try {
    // TODO: 调用发送验证码API
    // await sendVerifyCodeApi({ email: fullEmail, type: 'forgot' });

    // 开始倒计时
    isCountingDown.value = true;
    countDown.value = 60;
    const timer = setInterval(() => {
      if (countDown.value > 0) {
        countDown.value--;
        countDownText.value = `${countDown.value}秒后重试`;
      } else {
        clearInterval(timer);
        isCountingDown.value = false;
        countDownText.value = '发送验证码';
      }
    }, 1000);

    ElNotification({
      title: '成功',
      message: '验证码已发送到您的邮箱',
      type: 'success'
    });
  } catch (error) {
    ElNotification({
      title: '错误',
      message: '验证码发送失败，请稍后重试',
      type: 'error'
    });
  }
};

// 重置密码
const handleResetPassword = async () => {
  if (!forgotFormRef.value) return;

  try {
    const valid = await forgotFormRef.value.validate();
    if (valid) {
      loading.value = true;
      const fullEmail = forgotForm.email + emailSuffix.value;
      // TODO: 调用重置密码API
      // await resetPasswordApi({ ...forgotForm, email: fullEmail });

      ElNotification({
        title: '成功',
        message: '密码重置成功，请使用新密码登录',
        type: 'success'
      });
      // 触发重置成功事件
      emit('reset-success');
    }
  } catch (error) {
    ElNotification({
      title: '错误',
      message: '密码重置失败，请稍后重试',
      type: 'error'
    });
  } finally {
    loading.value = false;
  }
};
</script>

<style lang="scss" scoped>
@use '../index.scss';

:deep(.el-input) {
  height: 40px;
  line-height: 40px;

  .el-input__wrapper {
    padding-top: 0;
    padding-bottom: 0;
  }

  .el-input__inner {
    height: 40px;
    line-height: 40px;
  }
}

.password-strength {
  display: flex;
  align-items: center;
  margin-top: 4px;
  font-size: 12px;

  .strength-label {
    margin-right: 8px;
    color: #909399;
  }

  .strength-bars {
    display: flex;
    gap: 4px;
    margin-right: 8px;

    .strength-bar {
      width: 30px;
      height: 4px;
      background-color: #e4e7ed;
      border-radius: 2px;
      transition: all 0.3s;

      &.weak {
        background-color: #f56c6c;
      }

      &.medium {
        background-color: #e6a23c;
      }

      &.strong {
        background-color: #67c23a;
      }
    }
  }

  .strength-text {
    &.text-weak {
      color: #f56c6c;
    }
    &.text-medium {
      color: #e6a23c;
    }
    &.text-strong {
      color: #67c23a;
    }
  }
}

.emailSelect {
  width: 150px;
  height: 100%;
  :deep(.el-select__wrapper) {
    height: 100%;
  }
}
</style>
